package com.hissy.common.office.exporter;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * Created by zhangyanfei on 2019/10/8.
 * 导出表格
 *
 * @author zhangyanfei
 * @date 2019/10/08
 */
public class ExportTable {
    /**
     * 列名
     */
    public String[] columns;

    /**
     * 行
     */
    public List<String[]> rows;

    private Map<String, Object> row;

    public ExportTable() {
        rows = new ArrayList<>();
        row = new LinkedHashMap<>();
        columns = new String[0];
    }

    /**
     * 添加行
     */
    void addRow(Map<String, Object> row) {
        // 表头 先判断是否已经初始化了
        if (columns.length == 0) {
            columns = row.keySet().stream()
                .map(String::valueOf)
                .collect(Collectors.toList())
                .toArray(new String[0]);
        }

        // 添加行数据
        String[] rowData = new String[columns.length];
        String key;
        Object columnValue = null;
        for (int i = 0; i < columns.length; i++) {
            key = columns[i];
            if (row.containsKey(key)) {
                columnValue = row.get(key);
                rowData[i] = columnValue != null ? columnValue.toString() : "";
            }
        }
        rows.add(rowData);
    }

    /**
     * 添加行
     */
    public void addRow(Consumer<Map<String, Object>> action) {
        action.accept(row);
        addRow(row);
    }
}
